package tool;

import java.util.Enumeration;
import java.util.Hashtable;

import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;

import playlist.Crawler;

public class Mp3Browser {

	private Crawler midlet;
	private Mp3Handler handler;
	private Hashtable fileLists;

	public Mp3Browser(Crawler aMidlet) throws Throwable {
		super();
		midlet = aMidlet;
		fileLists = new Hashtable();
		
		setupLists();
	}
	
	private void setupLists() throws Throwable {
		String[] dirNames = midlet.getDirNames();
		
		for (int i = 0; i < dirNames.length; i++) {
			FileConnection connection
				= (FileConnection) Connector.open(dirNames[i]);
			Enumeration files = connection.list("*.mp3", true);
			connection.close();
			fileLists.put(dirNames[i], files);
		}
	}

	public void browse(Mp3Handler aHandler) throws Throwable {
		handler = aHandler;
		
		Enumeration keys = fileLists.keys();
		
		while (keys.hasMoreElements()) {
			String key = (String) keys.nextElement();
			Enumeration files = (Enumeration) fileLists.get(key);
			
			while (files.hasMoreElements()) {
				String mp3 = (String) files.nextElement();
				handler.handleNextMP3(key, mp3);
			}
		}
	}
	
}
